package com.l.controller.app;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.l.entity.Recharge;
import com.l.pay.app.AlipayConfig;
import com.l.service.RechargeService;

/**
 * 支付宝支付结果响应接口
 * 
 * @author 
 * @version 1.0
 * @return
 */
@Controller
@SuppressWarnings("all")
public class ReceiveAliPayController{
	@Autowired
	RechargeService rechargeService;
	
	@RequestMapping("/receivealipay")
	public String execute(HttpServletRequest request) throws AlipayApiException {
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (
		Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。
			/*try {
				valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
			params.put(name, valueStr);
		}
		
		// 商户订单号
		String out_trade_no = new String(request.getParameter("out_trade_no"));

		// 支付宝交易号
		String trade_no = new String(request.getParameter("trade_no"));
		
		// 交易状态
		String trade_status = new String(request.getParameter("trade_status"));
		
        // 3.签名验证(对支付宝返回的数据验证，确定是支付宝返回的)
        // 3.1调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ali_public_key, AlipayConfig.input_charset,AlipayConfig.sign_type);
		if (signVerified) {// 验证成功
			// ——请根据您的业务逻辑来编写程序——
			if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
				// 查询订单信息
				Recharge aliwxpay=rechargeService.query(out_trade_no);
				if (aliwxpay.getStatus()==0) {
					//修改订单状态
					rechargeService.upStatus(out_trade_no);
				}
			}
		}
		return "redirect:/select";
	}
}
